package com.wframe.project.former.web.marketing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.pageform.DataPageForm;
import com.frame.pageform.component.Json;
import com.wframe.project.former.dataservices.marketing.FillReductionService;
import com.wframe.project.former.dataservices.marketing.PromotionsService;
import com.wframe.project.former.dataservices.marketing.SingService;
import com.wframe.project.former.dataservices.products.ProductClassService;
import com.wframe.project.former.dataservices.products.ProductService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.*;

/**
 * Created by Administrator on 2017/6/14.
 */
public class FillReductionPage extends DataPageForm {
    private static FillReductionService fillReductionService = FillReductionService.getIntance();
    private ProductClassService classService = ProductClassService.getIntance();
    private PromotionsService promotionsService = PromotionsService.getIntance();
    private static SingService singService = SingService.getIntance();
    private ProductClassService pcservice = ProductClassService.getIntance();
    private ProductService service = ProductService.getIntance();
    private JdataBean bean;

    @Override
    public String show() throws Exception {
        bean = fillReductionService.moneyoffById(bean.getString("id"));
        if ("2".equals(bean.getString("product_type")) || "1".equals(bean.getString("product_type"))) {
            if ("2".equals(bean.getString("product_type"))) {
                List<JdataBean> productClassList = promotionsService.getSingleProductList(bean.getString("product_val"));
                for (JdataBean jdataBean : productClassList) {
                    jdataBean.put("price", promotionsService.getProducrPrice(String.valueOf(jdataBean.get("id"))));
                    jdataBean.put("moneyOffType", promotionsService.getProductMoneyOffTypeById(String.valueOf(jdataBean.get("id"))));
                    jdataBean.put("classname", pcservice.getProductClassName(String.valueOf(jdataBean.getString("id"))));
                    List<JdataBean> jdataBeans_attribute = service.queryAllModelAttrAndVal("1", String.valueOf(jdataBean.get("id")), 1);
                    for (JdataBean attr : jdataBeans_attribute) {
                        jdataBean.put(attr.getString("code"), attr.get("val"));
                    }
                }
                getRequest().setAttribute("productitems_to", productClassList);
            }
            if ("1".equals(bean.getString("product_type"))) {
                JdataBean singleProducData = promotionsService.getSingleProduct(bean.getString("product_val"));
                if (singleProducData != null) {
                    singleProducData.put("price", promotionsService.getProducrPrice(String.valueOf(singleProducData.get("id"))));
                    singleProducData.put("moneyOffType", promotionsService.getProductMoneyOffTypeById(String.valueOf(singleProducData.get("id"))));
                    singleProducData.put("classname", pcservice.getProductClassName(String.valueOf(singleProducData.getString("id"))));
                    List<JdataBean> jdataBeans_attribute = service.queryAllModelAttrAndVal("1", String.valueOf(singleProducData.get("id")), 1);
                    for (JdataBean attr : jdataBeans_attribute) {
                        singleProducData.put(attr.getString("code"), attr.get("val"));
                    }
                    getRequest().setAttribute("singleProducitem", singleProducData);
                }
            }

        }
        if ("3".equals(bean.getString("product_type"))) {
            String moneyOff_classid = bean.getString("product_val");
            getRequest().setAttribute("moneyOff_classid", moneyOff_classid);
        }
        getRequest().setAttribute("controlsales", promotionsService.promotionControlsale(bean.getInt("id")));
        String itemsmoney = bean.getString("items");

        return "/webadmin/marketing/fullcutListEdit.jsp";
    }

    @Override
    public String toDel() throws Exception {
        return null;
    }

    @Override
    public boolean toUpdate() throws Exception {
        try {
            JdataBean promotbasedata = new JdataBean();
            promotbasedata.put("name", bean.getString("name"));
            promotbasedata.put("time", bean.getString("time"));
            promotbasedata.put("start_time", bean.getString("start_time"));
            promotbasedata.put("end_time", bean.getString("end_time"));
            promotbasedata.put("promotion_type", 2);
            promotbasedata.put("platform", bean.getString("platform"));
            promotbasedata.put("description", bean.getString("description"));
            promotbasedata.put("sort_value", bean.getString("sort_value"));
            promotbasedata.put("district_description", bean.getString("district_description"));
            String proMotType = bean.getString("product_type");
            List<JdataBean> beanList = null;
            String productVal = bean.getString("product_val");
            String protype = "";   //修改前的状态

            //编辑修改类型时先将活动的商品所属组类型设置为空
            if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                JdataBean jdataBeanType = promotionsService.getBean(bean.getString("promotid"));
                protype = jdataBeanType.getString("product_type");
                JdataBean prodauct_edit = new JdataBean();
                prodauct_edit.put("product_type", null);
                Map key_pro_edit = new HashMap();
                key_pro_edit.put("id", bean.getString("promotid"));
                promotionsService.update(prodauct_edit.getDataMap(), key_pro_edit);
            }

            //已经有添加全部商品的活动
            if ("0".equals(proMotType) || "1".equals(bean.getString("classid")) && "3".equals(proMotType)) {
                beanList = fillReductionService.canCreate();
                if (beanList.size() != 0 ) {
                    if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                        JdataBean promotbasedatato = new JdataBean();
                        promotbasedatato.put("product_type", protype);
                        Map key_pro_edit = new HashMap();
                        key_pro_edit.put("id", bean.getString("promotid"));
                        promotionsService.update(promotbasedatato.getDataMap(), key_pro_edit);
                    }
                    getJsonObject().put("state", "no");
                    return false;
                }
            }

            //查询商品是否已经参加活动
            if ("2".equals(proMotType)) {
                List<String> ids = JSON.parseArray(productVal, String.class);
                if (ids.size() != 0) {
                    beanList = fillReductionService.canCreate(ids);
                    if (beanList.size() != 0 ) {
                        if(StringUtils.isNotBlank(bean.getString("promotid"))){
                            JdataBean promotbasedatato = new JdataBean();
                            promotbasedatato.put("product_type", protype);
                            Map key_pro_edit = new HashMap();
                            key_pro_edit.put("id", bean.getString("promotid"));
                            promotionsService.update(promotbasedatato.getDataMap(), key_pro_edit);
                        }
                        getJsonObject().put("state", "no");
                        return false;
                    }
                }
            }
            //查询类目是否参加了活动
            if ("3".equals(proMotType) && StringUtils.isNotBlank(bean.getString("classid"))) {
                beanList = fillReductionService.canCreate(bean.getString("classid"));
                if (beanList.size() != 0) {
                    if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                        JdataBean promotbasedatato = new JdataBean();
                        promotbasedatato.put("product_type", protype);
                        Map key_pro_edit = new HashMap();
                        key_pro_edit.put("id", bean.getString("promotid"));
                        promotionsService.update(promotbasedatato.getDataMap(), key_pro_edit);
                    }
                    getJsonObject().put("state", "no");
                    return false;
                }
            }
            //编辑
            if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                Map key = new HashMap();
                key.put("id", bean.getString("promotid"));
                JdataBean jdataBeanEdit = new JdataBean();

                String money_off = bean.getString("money_off");
                fillReductionService.addMoneyOff(bean.getString("promotid"), money_off);
                promotbasedata.put("product_type", protype);

                promotionsService.update(promotbasedata.getDataMap(), key);
                if ("0".equals(bean.getString("product_type"))) {
                    promotbasedata.put("product_type", 0);
                    promotionsService.update(promotbasedata.getDataMap(), key);
                }


                if ("2".equals(bean.getString("product_type"))) {
                    List<String> ids = JSON.parseArray(productVal, String.class);
                    if (ids.size() == 0) {
                        JdataBean promotProductnull = new JdataBean();
                        promotProductnull.put("product_type", null);
                        promotProductnull.put("product_val", null);
                        promotionsService.update(promotProductnull.getDataMap(), key);
                    }
                    if (ids.size() == 1) {
                        for (String id : ids) {
                            JdataBean promotSingLe = new JdataBean();
                            promotSingLe.put("product_type", 1);
                            promotSingLe.put("product_val", id);
                            promotionsService.update(promotSingLe.getDataMap(), key);
                        }
                    }
                    if (ids.size() > 1) {
                        promotbasedata.put("product_type", 2);
                        promotbasedata.put("product_val", bean.getString("promotid"));
                        promotionsService.update(promotbasedata.getDataMap(), key);
                        fillReductionService.promotProduct(bean.getString("promotid"), ids);
                    }

                }
                //编辑指定类目
                if ("3".equals(bean.getString("product_type"))) {
                    if ("null".equals(bean.getString("classid"))) {
                        promotbasedata.put("product_type", null);
                        promotbasedata.put("product_val", null);
                    } else {
                        promotbasedata.put("product_type", 3);
                        promotbasedata.put("product_val", bean.getString("classid"));
                    }

                    promotionsService.update(promotbasedata.getDataMap(), key);

                }
                org.json.JSONArray controlsales = null;
                if (StringUtils.isNotBlank(bean.getString("controlsales")))//保存控销数据
                    controlsales = new org.json.JSONArray(bean.getString("controlsales"));
                singService.addControlsalesSingLe(bean.getString("promotid"), controlsales, bean.getString("controlusers"));
            }
            //添加
            if (StringUtils.isBlank(bean.getString("promotid"))) {
//                promotbasedata.put("product_type", 1);
                String promotId = promotionsService.addPromotions(promotbasedata);
                String money_off = bean.getString("money_off");
                fillReductionService.addMoneyOff(promotId, money_off);
                Map key = new HashMap();
                key.put("id", promotId);
                if ("0".equals(bean.getString("product_type"))) {
                    JdataBean promotAll = new JdataBean();
                    promotAll.put("product_type", 0);
                    promotAll.put("weight", 2);
                    promotAll.put("second_priority", 0);
                    promotionsService.update(promotAll.getDataMap(), key);
                }

                if ("2".equals(bean.getString("product_type"))) {
                    List<String> ids = JSON.parseArray(productVal, String.class);
                    if (ids.size() == 0) {
                        JdataBean promotProductnull = new JdataBean();
                        promotProductnull.put("product_type", null);
                        promotProductnull.put("product_val", null);
                        promotProductnull.put("weight", 2);
                        promotProductnull.put("second_priority", 0);
                        promotionsService.update(promotProductnull.getDataMap(), key);
                    }
                    if (ids.size() == 1) {
                        for (String id : ids) {
                            JdataBean promotSingLeDate = new JdataBean();
                            promotSingLeDate.put("product_type", 1);
                            promotSingLeDate.put("product_val", id);
                            promotSingLeDate.put("weight", 2);
                            promotSingLeDate.put("second_priority", 0);

                            promotionsService.update(promotSingLeDate.getDataMap(), key);
                        }

                    }
                    if (ids.size() > 1) {
                        JdataBean promotdata = new JdataBean();
                        promotdata.put("product_val", promotId);
                        promotdata.put("product_type", 2);
                        promotdata.put("weight", 2);
                        promotdata.put("second_priority", 0);

                        promotionsService.update(promotdata.getDataMap(), key);
                        fillReductionService.promotProduct(promotId, ids);
                    }
                }
                //添加指定类目
                if ("3".equals(bean.getString("product_type"))) {
                    JdataBean promotClassdata = new JdataBean();
                    if ("null".equals(bean.getString("classid"))) {
                        promotClassdata.put("product_type", null);
                        promotClassdata.put("product_val", null);
                    } else {
                        promotClassdata.put("product_type", 3);
                        promotClassdata.put("product_val", bean.getString("classid"));
                    }
                    promotClassdata.put("weight", 2);
                    promotClassdata.put("second_priority", 0);
                    promotionsService.update(promotClassdata.getDataMap(), key);
                }


                org.json.JSONArray controlsales = null;
                if (StringUtils.isNotBlank(bean.getString("controlsales")))//保存控销数据
                    controlsales = new org.json.JSONArray(bean.getString("controlsales"));
                singService.addControlsalesSingLe(promotId, controlsales, bean.getString("controlusers"));
            }

            getJsonObject().put("state", "ok");
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存商品信息错误：", e);
            getJsonObject().put("state", e.getMessage());
        }
        return false;
    }

    @Override
    public String execute() throws Exception {
        setPagination(fillReductionService.queryFillReduction(bean, getPageSize_(), getPageNum()));
        return "/webadmin/marketing/fillReductionList.jsp";
    }

    public String classCommon() throws Exception {
        return "/webadmin/marketing/classifyCommon.jsp";
    }

    //选择商品
    public String chooseMoneyList() throws Exception {
        PageResult pr = fillReductionService.queryMoneyProduct(bean, 10, getPageNum());
        List<JdataBean> list = pr.getList();

        for (JdataBean product : list) {
            product.put("price", promotionsService.getProducrPrice(String.valueOf(product.get("id"))));
            product.put("moneyOffType", promotionsService.getProductMoneyOffTypeById(String.valueOf(product.get("id"))));
            if (product.getString("moneyOffType") != null) {
                if (product.getString("moneyOffType").contains("满赠促销")) {
                    product.put("product_type_money_off", "已参加满赠活动");
                }
                if ((product.getString("moneyOffType") != null && product.getString("moneyOffType").contains("满减促销"))) {
                    product.put("product_type_money_off", "已参加满减活动");
                }
            }
            List<JdataBean> jdataBeans = service.queryAllModelAttrAndVal("1", String.valueOf(product.get("id")), 1);
            for (JdataBean attr : jdataBeans) {
                product.put(attr.getString("code"), attr.get("val"));
            }
//            product.put("promotion_type", singService.queryType(product.getInt("id")));
//            product.put("promotiontype",promotionsService.queryType());
            product.put("classname", pcservice.getProductClassName(String.valueOf(product.getString("id"))));

        }
        setPagination(pr);
        return "/webadmin/marketing/moneyOffProductList.jsp";
    }

    //进入添加页面
    public String addMoneyOff() {
        return "/webadmin/marketing/fullcutListAdd.jsp";
    }

    public JdataBean getBean() {
        return bean;
    }

    public void setBean(JdataBean bean) {
        this.bean = bean;
    }
}
